// dd.js
import * as dd from 'dingtalk-jsapi'
import request from "@/utils/request.js";

function getQueryString(name) {
		let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		let r = window.location.search.substr(1).match(reg);
		if (r != null) {
				return unescape(r[2]);
		}
		return null;
}
/**
//免密登录
**/
let cb = function(){}
export function getCode(callback) {
	  cb = callback
    let corpId = getQueryString('corpId') || 'dingc2ebee6fdfd68866a1320dcb25e91351' //企业ID 见下图
        dd.ready(() => {
					// alert('ready=====')
            //使用SDK 获取免登授权码
						// console.log(1111111111);
            dd.runtime.permission.requestAuthCode({
                corpId: corpId,
                onSuccess: info => {
									// alert(`code:${info.code}`)
                    // 根据钉钉提供的api 获得code后,再次调用这个callback方法
                    // 由于是钉钉获取code是异步操作,不知道什么时候执行完毕
                    // callback 函数会等他执行完毕后在自己调用自己
										getToken(info.code)
                    // callback(info.code)
                },
                onFail: err => {
                    alert('fail')
                    alert(JSON.stringify(err))
                }
            })
        })
    // }
}

//获取token
export function getToken(code) {
	request.get('/dingtalk/gettoken', {
		appkey: "dingpqubgfblfrfvn1ue",
		appsecret: "y0HWOmiks7SaD7sLvHj7KXR9lPjp6s_5lqi8xHj3LD7vvgBeoIFnAq8gxWSxawTi"
	}).then(res=> {
		getUserId(code, res.access_token)
	})
}

//获取user_id
export function getUserId(code, token) {
	request.post(`/dingtalk/topapi/v2/user/getuserinfo?access_token=${token}`, {
		code: code
	}).then(res=> {
		res.result && getUserInfo(token, res.result.userid)
	})
}

//获取用户信息
export function getUserInfo(token, userid) {
	request.post(`/dingtalk/topapi/v2/user/get?access_token=${token}`, {
		userid: userid,
	}).then(res=> {
		uni.setStorageSync('userInfo', res.result || {});
		cb(res.result || {})
	})
}

// 获取用户信息